package com.fau.cm.timer;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.fau.cm.dao.IBaseDao;
import com.fau.cm.entity.MedicalAdmin;
import com.fau.cm.entity.MedicalCall;
import com.fau.cm.entity.MedicalCallCustomer;
import com.fau.cm.entity.MedicalCallEnd;
import com.fau.cm.entity.MedicalCallPending;
import com.fau.cm.entity.MedicalCallSMSPhrase;
import com.fau.cm.entity.MedicalCallSms;
import com.fau.cm.entity.MedicalCallTelInfo;
import com.fau.cm.entity.MedicalCallUntreated;
import com.fau.cm.entity.MedicalKeyValue;
import com.fau.cm.util.SystemConfig;

@Service
@Transactional(readOnly = true)
public class TimerTask {

	@Resource
	protected IBaseDao iBaseDao;
	
	/**
	 * @desc 每天晚上12点执行
	 * @author kangyj
	 * @datetime 2015年1月14日,下午3:08:29
	 */
	@Scheduled(cron = "0 0 0 * * ?")
	@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public void run() {
		this.findWasteCall();
		this.findCustomerBirth();
	}
	
	/**
	 * @desc 查询任务30天内是否成单，不成单改为废线任务
	 * @author kangyj
	 * @datetime 2015年1月14日,下午3:04:49
	 */
	@SuppressWarnings("unchecked")
	@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public void findWasteCall() {
		
		StringBuilder hql1 = new StringBuilder("from MedicalCallUntreated a where a.grade=? ");			// 未处理
		StringBuilder hql2 = new StringBuilder("from MedicalCallPending a where a.grade=? ");			// 待处理
		StringBuilder hql3 = new StringBuilder("from MedicalCallEnd a where a.grade=? ");				// 已结束
		
		List<MedicalCallUntreated> callUntList = this.iBaseDao.getBySql(hql1.toString(), null, SystemConfig.CALL_TASK_GRADE_USER);
		for(MedicalCallUntreated callUnt : callUntList) {
			Date allocateTime = DateUtils.addDays(callUnt.getAllocationTime(), SystemConfig.CALL_WASTE_TIME);
			if(new Date().after(allocateTime)) {
				MedicalCall call = new MedicalCall();
				BeanUtils.copyProperties(callUnt, call);
				call.setCenterId("");
				call.setGroupId("");
				call.setHandleUserId("");
				call.setGrade(SystemConfig.CALL_TASK_GRADE_INIT);
				call.setCategory(SystemConfig.CALL_WASTE_TYPE);
				this.iBaseDao.addObject(call);
				this.iBaseDao.deleteObject(callUnt);
			}
		}
		
		List<MedicalCallPending> callPenList = this.iBaseDao.getBySql(hql2.toString(), null, SystemConfig.CALL_TASK_GRADE_USER);
		for(MedicalCallPending callPen : callPenList) {
			Date allocateTime = DateUtils.addDays(callPen.getAllocationTime(), SystemConfig.CALL_WASTE_TIME);
			if(new Date().after(allocateTime)) {
				MedicalCall call = new MedicalCall();
				BeanUtils.copyProperties(callPen, call);
				call.setCenterId("");
				call.setGroupId("");
				call.setHandleUserId("");
				call.setGrade(SystemConfig.CALL_TASK_GRADE_INIT);
				call.setCategory(SystemConfig.CALL_WASTE_TYPE);
				this.iBaseDao.addObject(call);
				this.iBaseDao.deleteObject(callPen);
			}
		}
		
		List<MedicalCallEnd> callEndList = this.iBaseDao.getBySql(hql3.toString(), null, SystemConfig.CALL_TASK_GRADE_USER);
		for(MedicalCallEnd callEnd : callEndList) {
			Date allocateTime = DateUtils.addDays(callEnd.getAllocationTime(), SystemConfig.CALL_WASTE_TIME);
			if(new Date().after(allocateTime)) {
				MedicalCall call = new MedicalCall();
				BeanUtils.copyProperties(callEnd, call);
				call.setCenterId("");
				call.setGroupId("");
				call.setHandleUserId("");
				call.setGrade(SystemConfig.CALL_TASK_GRADE_INIT);
				call.setCategory(SystemConfig.CALL_WASTE_TYPE);
				this.iBaseDao.addObject(call);
				this.iBaseDao.deleteObject(callEnd);
			}
		}
		
	}
	
	/**
	 * @desc 查询客户生日
	 * @author liy
	 * @datetime 2015年2月14日,上午10:55:54
	 */
	@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public void findCustomerBirth() {
		String now = DateFormatUtils.format(new Date(), "yyyyMMdd");
		@SuppressWarnings("unchecked")
		List<MedicalCallCustomer> list = this.iBaseDao.getBySql("from MedicalCallCustomer a where a.birthDate is not null and DATE_FORMAT(a.birthDate,'%Y%m%d')=? ", null, now);
		for (MedicalCallCustomer medicalCallCustomer : list) {
			// 判断是否发送生日短信
			MedicalKeyValue keyValue = (MedicalKeyValue) this.iBaseDao.getObjectByHql("from MedicalKeyValue a where a.hospitalId=? and a.systemType=? and a.typeName=? and a.keyName=? ",
					medicalCallCustomer.getHospitalId(),
					SystemConfig.CM_SYSTEM_TYPE,
					SystemConfig.SMS_RM,
					SystemConfig.SMS_BIRTHDAY);
			// 1发送生日短信
			if(keyValue.getKeyValue().equals("1")){
				// 查找生日短信模版
				@SuppressWarnings("unchecked")
				List<MedicalCallSMSPhrase> phraseList = this.iBaseDao.getBySql("from MedicalCallSMSPhrase a where a.hospitalId=? and a.type=? ", null, medicalCallCustomer.getHospitalId(),SystemConfig.SMS_BIRTHDAY_KEY);
				MedicalCallSms callSms = new MedicalCallSms();
				if(phraseList.size() > 0){
					MedicalCallSMSPhrase smsPhrase = phraseList.get(0);
					String temp = smsPhrase.getContent().replace(SystemConfig.SMS_PLACEHOLDER, medicalCallCustomer.getName());
					callSms.setContent(temp);
					// 获取用户主要号码
					MedicalCallTelInfo callTelInfo = (MedicalCallTelInfo) this.iBaseDao.getObjectByHql("from MedicalCallTelInfo a where a.customerId=? and a.isMain=? ", medicalCallCustomer.getId(),SystemConfig.CUSTOMER_TEL_IS_MAIN);
					callSms.setPhoneNum(callTelInfo.getPhoneNum());
					MedicalAdmin admin = (MedicalAdmin) this.iBaseDao.getObjectByHql("from MedicalAdmin a where a.enterpriseId=? and a.isSuper=? ", medicalCallCustomer.getHospitalId(),SystemConfig.SUPER_ADMIN);
					callSms.setSendSeat(admin.getId());// 超级管理员
					callSms.setSendStatus(SystemConfig.SMS_NO_SEND_TYPE);
					callSms.setCenterId("0");
					callSms.setGroupId("0");
					callSms.setCustomerId(medicalCallCustomer.getId());
					callSms.setHospitalId(medicalCallCustomer.getHospitalId());
					this.iBaseDao.saveObject(callSms);
				}
			}
		}
	}
}
